﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Graphics.Implementation;
using Tesla.Math;
using Tesla.Util;

namespace Tesla.Graphics {
    /// <summary>
    /// Represents a cube where each face is a 2-Dimensional texture.
    /// </summary>
    public class TextureCube : Texture {
        internal TextureCubeImplementation _impl;

        /// <summary>
        /// Gets the API-specific implementation of this resource.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets the format of the texture resource.
        /// </summary>
        public override SurfaceFormat Format {
            get {
                return _impl.Format;
            }
        }

        /// <summary>
        /// Gets the number of mip map levels in the texture resource.
        /// </summary>
        public override int MipCount {
            get {
                return _impl.MipCount;
            }
        }

        /// <summary>
        /// Gets the texture dimensions, identifying the texture resource.
        /// </summary>
        public override TextureDimensions Dimensions {
            get {
                return TextureDimensions.Cube;
            }
        }

        /// <summary>
        /// Gets the width/height of each cube face.
        /// </summary>
        public int Size {
            get {
                return _impl.Size;
            }
        }

        /// <summary>
        /// For ISavable.
        /// </summary>
        protected TextureCube() {}

        //For FromFile...temp
        private TextureCube(TextureCubeImplementation impl) {
            _impl = impl;
        }

        /// <summary>
        /// Creates a new instance of <see cref="TextureCube"/>.
        /// </summary>
        /// <param name="size">The size (width/height) of each cube face.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public TextureCube(int size) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, false, SurfaceFormat.Color, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="TextureCube"/>.
        /// </summary>
        /// <param name="size">The size (width/height) of each cube face.</param>
        /// <param name="genMipMap">True if mip levels should be generated.</param>
        /// <param name="format">The surface format.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public TextureCube(int size, bool genMipMap, SurfaceFormat format) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, genMipMap, format, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="TextureCube"/>.
        /// </summary>
        /// <param name="size">The size (width/height) of each cube face.</param>
        /// <param name="genMipMap">True if mip levels should be generated.</param>
        /// <param name="format">The surface format.</param>
        /// <param name="initialData">The initial data for the first mip level.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public TextureCube(int size, bool genMipMap, SurfaceFormat format, DataBuffer[] initialData) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, genMipMap, format, initialData);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="TextureCube"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="size">The size (width/height) of each cube face.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails.</exception>
        public TextureCube(IRenderSystemProvider renderSystem, int size) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, false, SurfaceFormat.Color, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="TextureCube"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="size">The size (width/height) of each cube face.</param>
        /// <param name="genMipMap">True if mip levels should be generated.</param>
        /// <param name="format">The surface format.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails.</exception>
        public TextureCube(IRenderSystemProvider renderSystem, int size, bool genMipMap, SurfaceFormat format) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, genMipMap, format, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="TextureCube"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="size">The size (width/height) of each cube face.</param>
        /// <param name="genMipMap">True if mip levels should be generated.</param>
        /// <param name="format">The surface format.</param>
        /// <param name="initialData">The initial data for the first mip level.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating or writing to the underlying texture fails.</exception>
        public TextureCube(IRenderSystemProvider renderSystem, int size, bool genMipMap, SurfaceFormat format, DataBuffer[] initialData) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, genMipMap, format, initialData);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="TextureCube"/> is reclaimed by garbage collection.
        /// </summary>
        ~TextureCube() {
            Dispose(false);
        }

        /// <summary>
        /// Gets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="face">Cube map face to read from.</param>
        /// <param name="data">Array of data.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(CubeMapFace face, T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(face, data, 0, null, 0, data.Length);
            } catch(Exception e) {
                throw new TeslaException("Error reading from texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Gets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="face">Cube map face to read from.</param>
        /// <param name="data">Array of data.</param>
        /// <param name="startIndex">Starting index in the array to start writing to.</param>
        /// <param name="elementCount">Number of elements to read.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(CubeMapFace face, T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(face, data, 0, null, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error reading from texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Gets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="face">Cube map face to read from.</param>
        /// <param name="data">Array of data.</param>
        /// <param name="mipLevel">Mip map level to access.</param>
        /// <param name="subimage">Rectangle representing a sub-image of the 2D texture to read from, if null the whole image is read from.</param>
        /// <param name="startIndex">Starting index in the array to start writing to.</param>
        /// <param name="elementCount">Number of elements to read.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(CubeMapFace face, T[] data, int mipLevel, Rectangle? subimage, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(face, data, mipLevel, subimage, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error reading from texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the data to the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="face">Cube map face to write to.</param>
        /// <param name="data">Array of data.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(CubeMapFace face, T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(face, data, 0, null, 0, data.Length);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the data to the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="face">Cube map face to write to.</param>
        /// <param name="data">Array of data.</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(CubeMapFace face, T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(face, data, 0, null, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the data to the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array.</typeparam>
        /// <param name="face">Cube map face to write to.</param>
        /// <param name="data">Array of data.</param>
        /// <param name="mipLevel">Mip map level to access.</param>
        /// <param name="subimage">Rectangle representing a sub-image of the 2D texture to write to, if null the whole image is written to.</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(CubeMapFace face, T[] data, int mipLevel, Rectangle? subimage, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(face, data, mipLevel, subimage, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public override void Write(ISavableWriter output) {
            SurfaceFormat format = _impl.Format;
            int size = _impl.Size;
            int mipCount = _impl.MipCount;

            output.Write("Name", _impl.Name);
            output.WriteEnum<SurfaceFormat>("Format", format);
            output.Write("Size", size);
            output.Write("MipCount", mipCount);

            for(int i = 0; i < 6; i++) {
                for(int j = 0; j < mipCount; j++) {
                    byte[] byteBuffer = new byte[MemoryHelper.CalculateMipSize(size, size, 1, j, format)];
                    _impl.GetData<byte>((CubeMapFace) i, byteBuffer, j, null, 0, byteBuffer.Length);
                    output.Write(String.Format("CubeMapFace: {0}, MipLevel{1}", ((CubeMapFace)i).ToString(), j), byteBuffer);
                }
            }
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying implementation fails or the render
        /// system is not set.</exception>
        public override void Read(ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            String name = input.ReadString();
            SurfaceFormat format = input.ReadEnum<SurfaceFormat>();
            int size = input.ReadInt();
            int mipCount = input.ReadInt();

            try {
                _impl = renderSystem.CreateTextureCubeImplementation(size, mipCount > 1, format, null);
                for(int i = 0; i < 6; i++) {
                    for(int j = 0; j < mipCount; j++) {
                        byte[] byteBuffer = input.ReadByteArray();
                        _impl.SetData<byte>((CubeMapFace) i, byteBuffer, j, null, 0, byteBuffer.Length);
                    }
                }
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }
    }
}
